import React, { useEffect, useState } from 'react'
import { Button, Table, Popconfirm, Modal, Tree } from 'antd';
import axios from 'axios';

export default function RoleList() {
  const [dataSource, setDataSource] = useState([])
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [treeData, setTreeData] = useState([])
  const [currentRight, setCurrentRight] = useState([])
  const [currentID, setCurrentID] = useState()
  // 角色数据
  useEffect(() => {
    axios.get('/roles').then(res => {
      // console.log(res)
      setDataSource(res.data)
    })
  }, [])

  // 权限数据
  useEffect(() => {
    axios.get('/rights?_embed=children').then(res => {
      // console.log(res)
      setTreeData(res.data)
    })
  }, [])

  // 删除
  const deleteItem = (item) => {
    // console.log(item)
    setDataSource(dataSource.filter(data => data.id !== item.id))
    axios.delete(`/roles/${item.id}`)
  }
  // 确认修改
  const handleOk = () => {
    setIsModalOpen(false)
    // console.log(currentRight)
    // 页面同步
    setDataSource(dataSource.map(item => {
      if (item.id === currentID) {
        return {
          ...item,
          rights: currentRight
        }
      } else {
        // console.log(item)
        return item
      }
    }))
    // 同步给后端
    axios.patch(`/roles/${currentID}`, {
      rights: currentRight
    })
  }
  // 树形控件的选择
  const onCheck = (checkedKeys) => {
    // console.log(checkedKeys)
    setCurrentRight(checkedKeys.checked)
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
    },
    {
      title: '操作',
      render: (item) => {
        return <div>
          <Popconfirm
            title="删除"
            description="你确定要删除吗"
            onConfirm={() => deleteItem(item)}
            okText="确定"
            cancelText="取消"
          >
            <Button type='primary' danger >删除</Button>
          </Popconfirm>
          <Button type='primary' onClick={() => { setIsModalOpen(true); setCurrentRight(item.rights); setCurrentID(item.id) }}>编辑</Button>
          <Modal title="路由分配" open={isModalOpen} onOk={handleOk} onCancel={() => { setIsModalOpen(false) }}>
            <Tree
              checkable
              checkedKeys={currentRight}
              onCheck={onCheck}
              treeData={treeData}
              checkStrictly={true}
            />
          </Modal>
        </div>
      },
    },
  ];


  return (
    <Table dataSource={dataSource} columns={columns} rowKey={(record) => record.id} />
  )
}
